-- This file is part of the Fantasy Grounds Open Foundation Ruleset project. 
-- For the latest information, see http://www.fantasygrounds.com/
--
-- Copyright 2008 SmiteWorks Ltd.
--
-- This file is provided under the Open Game License version 1.0a
-- Refer to the license.html file for the full license text
--
-- All producers of work derived from this material are advised to
-- familiarize themselves with the license, and to take special
-- care in providing the definition of Product Identity (as specified
-- by the OGL) in their products.
--
-- All material submitted to the Open Foundation Ruleset project must
-- contain this notice in a manner applicable to the source file type.


function applyModifierStackToRoll(draginfo)
	if ModifierStack.isEmpty() then
		--[[ do nothing ]]
	elseif draginfo.getNumberData() == 0 and draginfo.getDescription() == "" then
		draginfo.setDescription(ModifierStack.getDescription());
		draginfo.setNumberData(ModifierStack.getSum());
	else
		local originalnumber = draginfo.getNumberData();
		local numstr = tostring(originalnumber);
		if originalnumber > 0 then
			numstr = "+" .. originalnumber;
		end

		local moddesc = ModifierStack.getDescription(true);
		local desc = draginfo.getDescription();
		
		if numstr ~= "0" then
			desc = desc .. " " .. numstr;
		end
		if moddesc ~= "" then
			desc = desc .. " (" .. moddesc .. ")";
		end
		
		draginfo.setDescription(desc);
		draginfo.setNumberData(draginfo.getNumberData() + ModifierStack.getSum());
	end
	
	if PreferenceManager.getValue("interface_resetmodifierstack") then
		ModifierStack.reset();
	end
end

function onDiceLanded(draginfo)
	if ChatManager.getDieRevealFlag() then
		draginfo.revealDice(true);
	end

	local handler = ChatManager.getDiceHandler(draginfo);
	
	if handler then
		return handler(draginfo);
	elseif draginfo.isType("dice") then
		applyModifierStackToRoll(draginfo);
	end
end

function onDrop(x, y, draginfo)
	if draginfo.getType() == "number" then
		applyModifierStackToRoll(draginfo);
	end
end

function moduleActivationRequested(module)
	local msg = {};
	msg.text = "Players have requested permission to load '" .. module .. "'";
	msg.font = "systemfont";
	msg.icon = "indicator_moduleloaded";
	addMessage(msg);
end

function moduleUnloadedReference(module)
	local msg = {};
	msg.text = "Could not open sheet with data from unloaded module '" .. module .. "'";
	msg.font = "systemfont";
	addMessage(msg);
end

function onInit()
	ChatManager.registerControl(self);
	
	if User.isHost() then
		Module.onActivationRequested = moduleActivationRequested;
	end

	Module.onUnloadedReference = moduleUnloadedReference;
end

function onClose()
	ChatManager.registerControl(nil);
end
